package com.jqk.shoporder.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jqk.shoporder.bean.TblOrderEvent;
import com.jqk.shoporder.service.TblOrderEventService;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author jqk
 * @date 2020/7/30
 */
@Component
public class OrderTask {

    @Autowired
    private TblOrderEventService tblOrderEventService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    private static  final String topic ="order-topic";

    @Scheduled(cron="0/5 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void task(){
        // 查出事件表中状态为 1 的事件
        List<TblOrderEvent> events = tblOrderEventService.query().eq("order-type", "1").list();
        if(CollectionUtils.isNotEmpty(events)){
            List<Message> messages=new ArrayList<>(events.size());
            // 将事件状态修改，并封装成消息类型
            List<TblOrderEvent> eventList = events.stream().peek(item -> {
                messages.add(new Message(topic, JSONObject.toJSONString(item).getBytes()));
                item.setOrderType("2");
            }).collect(Collectors.toList());
            // 修改数据库中的事件
            tblOrderEventService.saveOrUpdateBatch(eventList);
            // 批量发送消息
            rocketMQTemplate.syncSend(topic,messages);
        }
    }

}
